<?php

namespace app\admin\controller;

use app\api\model\Privatechat;
use app\api\model\YaoqingRecords;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use think\Db;

class Rewardcenter extends Common {
	public function invite()
	{
        $users = Db::name('user')->where(['yqr'=>['<>', '']])->whereTime('register_datetime', 'last month')->cache(600)->column('id');
        $activeUsers = Db::name('user_data')->where(['user_id'=>['in', $users]])->where('topup > 0 or income > 0')->fetchSql(false)->cache(600)->column('user_id');
        $parents = Db::name('user')->where(['id'=>['in', $activeUsers]])->cache(600)->column('yqr');
        foreach ($parents as &$value) {
        	$value = strtoupper($value);
        }
        $parentUsers = Db::name('user')->where(['yqm'=>['in', $parents]])->field('id,name,phone,yqm')->cache(600)->select();
        $parents=array_count_values($parents);
        foreach ($parentUsers as $key => $value) {
            $num = $parents[$value['yqm']];
            $parentUsers[$key]['num'] = $num;
            $parentUsers[$key]['reward'] = $num * 15;
            $parentUsers[$key]['inviteUser'] = Db::name('user')->where(['yqr'=>$value['yqm']])->whereTime('register_datetime', 'last month')->cache(600)->column('id');
            $parentUsers[$key]['activeUser'] = Db::name('user')->where(['id'=>['in', $activeUsers], 'yqr'=>$value['yqm']])->cache(600)->column('id');
            $parentUsers[$key]['invite'] = sizeof($parentUsers[$key]['inviteUser']);
        }
        $this->assign('data', $parentUsers);
        return $this->fetch();
	}
    public function invitebak()
    {
        $minreward = 100;
        $users = Db::name('user')->where(['yqr'=>['<>', '']])->whereTime('register_datetime', 'last month')->cache(600)->column('id,yqr');
        $activeUsers = Db::name('user_data')->where(['user_id'=>['in', array_keys($users)]])->where('topup > 0 or income > 0')->fetchSql(false)->cache(600)->column('user_id');
        $parentUsers = Db::name('user')->where(['yqm'=>['in', array_values($users)]])->field('id,name,phone,yqm')->cache(600)->select();
        foreach ($parentUsers as $key => $value) {
            $num = 0;
            $inviteUser = Db::name('user')->where(['yqr'=>$value['yqm']])->whereTime('register_datetime', 'last month')->cache(600)->order('id asc')->column('id');
            $parentUsers[$key]['inviteUser'] = $inviteUser;
            $overwhere = '';
            $inviteUserNum = sizeof($inviteUser);
            if ($inviteUserNum > $minreward) {
                $num = $minreward;
                $overwhere = 'id > ' . $inviteUser[$minreward];
                $parentUsers[$key]['activeUser'] = Db::name('user')->where(['id'=>['in', $activeUsers], 'yqr'=>$value['yqm']])->where($overwhere)->cache(600)->fetchSql(false)->column('id');
            } else {
                $num = $inviteUserNum;
                $parentUsers[$key]['activeUser'] = [];
            }
            $activeUser = sizeof($parentUsers[$key]['activeUser']);
            $parentUsers[$key]['invite'] = $inviteUserNum;
            $parentUsers[$key]['num'] = $activeUser;
            $parentUsers[$key]['min'] = $num;
            $parentUsers[$key]['minUsers'] = array_slice($inviteUser, 0, $minreward);
            $parentUsers[$key]['count'] = $num + $activeUser;
            $parentUsers[$key]['reward'] = $parentUsers[$key]['count'] * 15;
        }
        $this->assign('data', $parentUsers);
        return $this->fetch();
    }
	public function recharge()
	{
        $timenow = time();
        $monthstart = strtotime(date('Y-m') . '-01');
        $userTeam = Db::name('user_team')->where('send_recharge_time < ' . $monthstart . ' and one_recharge_last_month >= 25000')->fetchSql(false)->order('one_recharge_last_month desc')->select();
        $users = Db::name('user')->where(['id'=>['in',array_column($userTeam, 'user_id')], 'reg'=>1, 'delete_time'=>0])->column('id');
        foreach ($userTeam as $key => $value) {
            if (!in_array($value['user_id'], $users)) {
                unset($userTeam[$key]);continue;
            }
            // if ($value['one_recharge_last_month'] > 250000) {
            //     $recharge_reward = $value['one_recharge_last_month'] * 3 / 100;
            // } else if ($value['one_recharge_last_month'] >= 25000) {
                $recharge_reward = $value['one_recharge_last_month'] * 1 / 100;
            // }
            $recharge_reward = $recharge_reward > 5000 ? 5000 : $recharge_reward;
            $userTeam[$key]['reward'] = round($recharge_reward, 2);
            $userTeam[$key]['childs'] = explode(',', $value['one']);
        }
        $this->assign('data', $userTeam);
        return $this->fetch();
	}
	public function active()
	{
        $timenow = time();
        $monthstart = strtotime(date('Y-m') . '-01');
        $userTeam = Db::name('user_team')->where('send_shouyi_time < ' . $monthstart . ' and total_shouyi_last_month >= 300000')->fetchSql(false)->select();
        foreach ($userTeam as $key => $value) {
            // if ($value['total_shouyi_last_month'] > 1000000) {
            //     $shouyi_reward = $value['total_shouyi_last_month'] * 2 / 100;
            // } else if ($value['total_shouyi_last_month'] >= 300000) {
                $shouyi_reward = $value['total_shouyi_last_month'] * 1 / 100;
            // }
            $shouyi_reward = $shouyi_reward > 5000 ? 5000 : $shouyi_reward;
            $userTeam[$key]['reward'] = round($shouyi_reward, 2);
        }
        $this->assign('data', $userTeam);
        return $this->fetch();
	}


    // 邀请奖励
    public function InvitationReward()
    {
    	if(cache('InvitationReward')) {
	        return ['err' => '重复操作'];
    	}
    	$day = date('d');
    	if ($day != 1 && !cache('InvitationRewardConfirm')) {
    		cache('InvitationRewardConfirm', $day, 300);
	        return ['err' => '今日不是月初一号，本次发奖取消，如确定需要发奖可在5分钟内再次发起'];
    	}
        $timenow = time();
        $users = Db::name('user')->where(['yqr'=>['<>', '']])->whereTime('register_datetime', 'last month')->cache(600)->column('id');
        $activeUsers = Db::name('user_data')->where(['user_id'=>['in', $users]])->where('topup > 0 or income > 0')->fetchSql(false)->cache(600)->column('user_id');
        $parents = Db::name('user')->where(['id'=>['in', $activeUsers]])->cache(600)->column('yqr');
        foreach ($parents as &$value) {
        	$value = strtoupper($value);
        }
        $parentUsers = Db::name('user')->where(['yqm'=>['in', $parents]])->field('id,yqm')->cache(600)->select();
        $parents=array_count_values($parents);
        foreach ($parentUsers as $key => $value) {
            $num = $parents[$value['yqm']];
            YaoqingRecords::index($value['id'], 0, $num * 15, '平台月奖励-邀请奖', 1, '', 0);
        }
        cache('InvitationReward', $timenow, 600);
        return ['ret' => '操作成功'];
    }
    // 充值奖励
    public function RechargeReward()
    {
        if(cache('RechargeReward')) {
            return ['err' => '重复操作'];
        }
        $day = date('d');
        if ($day != 1 && !cache('RechargeRewardConfirm')) {
            cache('RechargeRewardConfirm', $day, 300);
            return ['err' => '今日不是月初一号，本次发奖取消，如确定需要发奖可在5分钟内再次发起'];
        }
        $timenow = time();
        $monthstart = strtotime(date('Y-m') . '-01');
        $userTeam = Db::name('user_team')->where('send_recharge_time < ' . $monthstart . ' and one_recharge_last_month >= 25000')->fetchSql(false)->select();
        // var_dump($userTeam);exit;
        foreach ($userTeam as $key => $value) {
            // if ($value['one_recharge_last_month'] > 250000) {
            //     $recharge_reward = $value['one_recharge_last_month'] * 3 / 100;
            // } else if ($value['one_recharge_last_month'] >= 25000) {
                $recharge_reward = $value['one_recharge_last_month'] * 1 / 100;
            // }
            $recharge_reward = $recharge_reward > 5000 ? 5000 : $recharge_reward;

            Db::name('user_team')->where(['id'=>$value['id']])->update([
                'recharge_reward' => $recharge_reward,
                'send_recharge_time' => $timenow
            ]);
            YaoqingRecords::index($value['user_id'], 0, $recharge_reward, '平台月奖励-充值奖', 1, '', 0);
        }
        cache('RechargeReward', $timenow, 600);
        return ['ret' => '操作成功'];
    }
    // 充值奖励(勾选)
    public function RechargeReward2()
    {
        $all = input('delAll/a');
        $timenow = time();
        $userTeam = Db::name('user_team')->where(['user_id'=>['in', $all]])->fetchSql(false)->select();
        if (sizeof($userTeam) == 0) {
            return ['err' => '未选择数据'];
        }
        foreach ($userTeam as $key => $value) {
            // if ($value['one_recharge_last_month'] > 250000) {
            //     $recharge_reward = $value['one_recharge_last_month'] * 3 / 100;
            // } else if ($value['one_recharge_last_month'] >= 25000) {
                $recharge_reward = $value['one_recharge_last_month'] * 1 / 100;
            // }
            $recharge_reward = $recharge_reward > 5000 ? 5000 : $recharge_reward;

            Db::name('user_team')->where(['id'=>$value['id']])->update([
                'recharge_reward' => $recharge_reward,
                'send_recharge_time' => $timenow
            ]);
            YaoqingRecords::index($value['user_id'], 0, $recharge_reward, '平台月奖励-充值奖', 1, '', 0);
        }
        return ['ret' => '操作成功'];
    }
    public function exportRechargeReward()
    {
        $monthstart = strtotime(date('Y-m'));
        $userTeam = Db::name('user_team')->where('date_update_time > ' . $monthstart . ' and one_recharge_last_month >= 25000')->fetchSql(false)->order('one_recharge_last_month desc')->select();
        $data = [];
        $users = Db::name('user')->where(['id'=>['in',array_column($userTeam, 'user_id')], 'reg'=>1, 'delete_time'=>0])->column('id');
        foreach ($userTeam as $key => $value) {
            if (!in_array($value['user_id'], $users)) {
                unset($userTeam[$key]);continue;
            }
            $recharge_reward = 0;
            // if ($value['one_recharge_last_month'] > 250000) {
            //     $recharge_reward = $value['one_recharge_last_month'] * 3 / 100;
            // } else if ($value['one_recharge_last_month'] >= 25000) {
                $recharge_reward = $value['one_recharge_last_month'] * 1 / 100;
            // }
            $recharge_reward = $recharge_reward > 5000 ? 5000 : $recharge_reward;
            if ($recharge_reward) {
                $data[] = [
                    'user_id'=>$value['user_id'],
                    'one_recharge_last_month'=>$value['one_recharge_last_month'],
                    'reward' => $recharge_reward,
                    'recharge_reward'=>$value['recharge_reward'],
                    'send_recharge_time'=>$value['send_recharge_time'] ? date('Y-m-d H:i:s', $value['send_recharge_time']) : '',
                ];
            }
        }
        if (sizeof($data)) {
            $this->ExportToExcel($data);
        }
    }

    public function ExportToExcel($data)
    {
        $spreadsheet = new Spreadsheet();

        $spreadsheet->setActiveSheetIndex(0)
            ->setCellValue('A1', '用户ID')
            ->setCellValue('B1', '一级下级总充值')
            ->setCellValue('C1', '预估奖励')
            ->setCellValue('D1', '上次发放奖励')
            ->setCellValue('E1', '上次发放时间');
        $spreadsheet->getActiveSheet()->setTitle('充值奖');
        $i = 2;
        foreach ($data as $v) {
            $spreadsheet->getActiveSheet()
                ->setCellValue('A' . $i, $v['user_id'])
                ->setCellValue('B' . $i, $v['one_recharge_last_month'])
                ->setCellValue('C' . $i, $v['reward'])
                ->setCellValue('D' . $i, $v['recharge_reward'])
                ->setCellValue('E' . $i, $v['send_recharge_time']);
            $i++;
        }
        $spreadsheet->getActiveSheet()
            ->getColumnDimension('A')
            ->setWidth(15);
        $spreadsheet->getActiveSheet()
            ->getColumnDimension('B')
            ->setWidth(15);
        $spreadsheet->getActiveSheet()
            ->getColumnDimension('C')
            ->setWidth(15);
        $spreadsheet->getActiveSheet()
            ->getColumnDimension('D')
            ->setWidth(15);
        $spreadsheet->getActiveSheet()
            ->getColumnDimension('E')
            ->setWidth(20);
        $spreadsheet->setActiveSheetIndex(0);
        ob_clean();
        header('Content-Type: application/vnd.ms-excel;charset=UTF-8');
        header('content-type:application/octet-stream');
        header('Cache-Control: max-age=0');
        header("Content-Type:application/force-download");
        header("Content-Type:application/download");
        //header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="' . time() . microtime(true) . '.xlsx"');
        //header('Cache-Control: max-age=0');
        $writer = new Xlsx($spreadsheet);

        $writer->save('php://output');
        exit;
    }



    // 活跃奖励
    public function ActiveReward()
    {
    	if(cache('ActiveReward')) {
	        return ['err' => '重复操作'];
    	}
    	$day = date('d');
    	if ($day != 1 && !cache('ActiveRewardConfirm')) {
    		cache('ActiveRewardConfirm', $day, 300);
	        return ['err' => '今日不是月初一号，本次发奖取消，如确定需要发奖可在5分钟内再次发起'];
    	}
        $timenow = time();
        $monthstart = strtotime(date('Y-m') . '-01');
        $userTeam = Db::name('user_team')->where('send_shouyi_time < ' . $monthstart . ' and total_shouyi_last_month >= 300000')->fetchSql(false)->select();
        // var_dump($userTeam);exit;
        foreach ($userTeam as $key => $value) {
            // if ($value['total_shouyi_last_month'] > 1000000) {
            //     $shouyi_reward = $value['total_shouyi_last_month'] * 2 / 100;
            // } else if ($value['total_shouyi_last_month'] >= 300000) {
                $shouyi_reward = $value['total_shouyi_last_month'] * 1 / 100;
            // }
            $shouyi_reward = $shouyi_reward > 5000 ? 5000 : $shouyi_reward;
            Db::name('user_team')->where(['id'=>$value['id']])->update([
                'shouyi_reward' => $shouyi_reward,
                'send_shouyi_time' => $timenow
            ]);
            YaoqingRecords::index($value['user_id'], 0, $shouyi_reward, '平台月奖励-活跃奖', 1, '', 0);
        }
        cache('ActiveReward', $timenow, 600);
        return ['ret' => '操作成功'];
    }
}